package com.paddyi.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.paddyi.commons.http.HttpResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: paddyi
 * @description: 自定义过滤器，ajax请求数据 以json格式返回
 * @author: paddy
 * @create: 2019-08-03 15:01
 **/
public class JsonFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

//            if (isAjax(httpRequest)) {
//                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
//                httpServletResponse.setStatus(401);
//                return false;
//            } else {
//                saveRequestAndRedirectToLogin(request, response);
//            }
            httpResponse.setContentType("text/html;charset=UTF-8");
//            httpResponse.addHeader("Access-Control-Allow-Origin", "http://www.paddyi.com");
//            httpResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//            httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
//            httpResponse.addHeader("Access-Control-Allow-Headers",
//                    "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");
            HttpResult result = new HttpResult();
            result.setMsg("未登录！");
            result.setCode(401);
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(result);
            httpResponse.getWriter().write(data);
            return false;
        }
    }

    /*
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }
}
